
import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import { ElMessage } from 'element-plus'
import userInfoApi, { type UserInfoModel } from '../api/userinfo';
interface UserInfoState {
    token: string,
    userInfo: UserInfoModel
}

const initUserInfo = () => ({
    createTime: '',
    gender: '',
    headImg: '',
    id: 0,
    loginName: '',
    name: '',
    nickName: '',
    operateTime: '',
    passwd: '',
    phoneNum: '',
    status: '',
    userLevel: '',
    birthday: null,
    email: null,
    openId: null,
})
export const useUserInfoStore = defineStore('userInfo', {

    state: (): UserInfoState => ({
        token: getToken() as string ,
        userInfo:  initUserInfo(),
        // menuRoutes: []
    }),

    actions: {

        async login(phone: string, password: string) {
            ;
            
            try {
                let result = await userInfoApi.PostLogin({ phone, password })
                this.token = result.token // 存到pinia的state中
          
                
                setToken(result.token)
               return Promise.resolve(result.token)
                
                
            } catch (error) {
                ElMessage.error('登录失败,请重试')
                return Promise.reject(error)
            }
        },
        async getInfos() {
           
            try {
                let result = await userInfoApi.getInfo()
                
                this.userInfo = result; // 存储个人信息

            } catch (error) {
                // ElMessage.error('获取个人信息失败,请重试')
                return Promise.reject(error)
            }
        },
        async reset() {
            try {
                await userInfoApi.logout()
               
            } catch (error) {
                console.error('登出失败', error)
            } finally {
                removeToken()
                this.token = ''
                // 重置个人信息
                // console.log("重置个人信息");
                
                this.userInfo = initUserInfo()
                return Promise.resolve(123)
                
            }
        },
    },
});
